import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年05月06日 09:19
 */
class DateRangePick extends StatefulWidget {
  final String title;
  final String startTime;
  final String endTime;
  final Function(String, String)onConfirm;
  const DateRangePick(this.title,this.startTime, this.endTime, this.onConfirm,{super.key});

  @override
  State<DateRangePick> createState() => _DateRangePickState();
}

class _DateRangePickState extends State<DateRangePick> {
  int startSelected = 0;
  int endSelected = 0;
  List<String> dateList = [];
  FixedExtentScrollController startScrollController = FixedExtentScrollController();
  FixedExtentScrollController endScrollController = FixedExtentScrollController();
  String startTime = '00"00';
  String endTime= '24"00';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initData();
    startTime = widget.startTime;
    endTime = widget.endTime;
    _handeInitDate(startTime,endTime);
    Log.d('startTime==' + startTime.toString());
    Log.d('endTime==' + endTime.toString());
  }

  initData() {
    for (int i = 0; i < 24; i++) {
      if (i < 10) {
        dateList.add('0$i:00');
        dateList.add('0$i:30');
      } else {
        dateList.add('$i:00');
        dateList.add('$i:30');
      }
    }
    dateList.add('24:00');
    return dateList;
  }

  @override
  Widget build(BuildContext context) {


    return Container(
        height: 280,
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        width: ScreenUtil().screenWidth,
        child: Column(
          children: [
            Container(
              height: 50,
              child:
                  Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                Gaps.hGap16,
                MyGestureDetector(onTap: (){
                  Navigator.pop(context);
                }, child: Text(
                  ResKey.cancel.tr,
                  style: TextStyle(
                    color: Colour.mainTextColor,
                    fontSize: 16.sp,
                  ),
                )),
                Spacer(),
                Text(
                  widget.title,
                  style: TextStyle(
                      color: Colour.mainTextColor,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500),
                ),
                Spacer(),
                    MyGestureDetector(onTap: (){
                      setState(() {
                        startTime = dateList[startSelected];
                        endTime  = dateList[endSelected];
                        widget.onConfirm(startTime, endTime);
                        Navigator.pop(context);
                      });
                    }, child: Text(
                  ResKey.sure.tr,
                  style: TextStyle(
                    color: Colour.primaryColor,
                    fontSize: 16.sp,
                  ),
                )),
                Gaps.hGap16,
              ]),
            ),
            Container(
              height: 0.5,
              color: Colour.dividerColor,
            ),
            Expanded(
                child: Row(
              children: [
                Container(
                    width: 100,
                    child: CupertinoPicker(
                      scrollController: startScrollController,
                        backgroundColor: Colors.white,
                        useMagnifier: true,
                        itemExtent: 40,
                        selectionOverlay: _selectionOverlayWidget(),
                        onSelectedItemChanged: (position) {
                          print('The position is $position');
                          setState(() {
                            _handleIllegalData(position,false);
                          });
                        },
                        children: getListWidgets(startSelected))),
                Spacer(),
                Container(
                  child: Text(
                    ResKey.to.tr,
                    style: ytTextStyle(
                        color: Colour.mainTextColor,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),
                ),
                Spacer(),
                Container(
                  width: 100,
                  child: CupertinoPicker(
                      scrollController: endScrollController,
                      backgroundColor: Colors.white,
                      useMagnifier: true,
                      itemExtent: 40,
                      selectionOverlay: _selectionOverlayWidget(),
                      onSelectedItemChanged: (position) {
                        print('The position is $position');
                        setState(() {
                          endSelected = position;
                          _handleIllegalData(position,true);
                        });
                      },
                      children: getListWidgets(endSelected)),
                ),
              ],
            )),
          ],
        ));
  }

  _handeInitDate(String startTime, String endTime) {
    for (int i = 0; i < dateList.length; i++) {
      if (dateList[i] == startTime) {
        startSelected = i;
        startScrollController = FixedExtentScrollController(initialItem: startSelected);
      }
      if (dateList[i] == endTime) {
        endSelected = i;
        endScrollController = FixedExtentScrollController(initialItem: endSelected);
      }
    }
  }
///如果开始时间大于结束时间,需要重置数据
  _handleIllegalData(int position,bool isEnd){
    if(isEnd){
      endSelected = position;
    }else{
      startSelected = position;
    }
    if(startSelected > endSelected && startSelected != dateList.length){
      endSelected = startSelected + 1;
      endScrollController.animateToItem(endSelected, duration: const Duration(milliseconds: 500), curve:Curves.ease);
    }
      setState(() {

      });
  }
  List<Widget> getListWidgets(int startSelected) {
    List<Widget> list = [];
    for (int i = 0; i < dateList.length; i++) {
      list.add(itemWidget(dateList[i], startSelected, i, false));
    }
    return list;
  }

  itemWidget(String value, int startSelected, int index, bool isEnd) {
    if(isEnd){
      return Container(
          color: Colors.white,
          alignment: Alignment.center,
          height: 40,
          child: Text(
            value,
            style: ytTextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: index == endSelected
                    ? Colour.primaryColor
                    : Colour.mainTextColor),
          ));
    }else{
      return Container(
          color: Colors.white,
          alignment: Alignment.center,
          height: 40,
          child: Text(
            value,
            style: ytTextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: index ==  startSelected
                    ? Colour.primaryColor
                    : Colour.mainTextColor),
          ));
    }

  }

  // 中间分割线
  Widget _selectionOverlayWidget() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, right: 0),
      child: Column(
        children: [
          const Divider(
            height: 0.5,
            color: Colour.dividerColor,
          ),
          Expanded(child: Container()),
          const Divider(
            height: 0.5,
            color: Colour.dividerColor,
          ),
        ],
      ),
    );
  }
}
